package handler

import (
	"encoding/json"
	"flag"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"zg3zy9/api/request"
	"zg3zy9/inits"
	"zg3zy9/interface/models"
)

var addr = flag.String("addr", "localhost:8080", "http service address")

func GetFail(conn *websocket.Conn, code string, msg string) {

	resp := request.WsResp{
		Code: code,
		Msg:  msg,
		Data: nil,
	}
	marshal, err := json.Marshal(resp)
	if err != nil {
		return
	}
	err = conn.WriteMessage(websocket.TextMessage, marshal)
	if err != nil {
		return
	}
}
func SuccessFs(conn *websocket.Conn, data interface{}) {

	resp := request.WsResp{
		Code: "200",
		Msg:  "成功",
		Data: data,
	}
	marshal, err := json.Marshal(resp)
	if err != nil {
		return
	}
	err = conn.WriteMessage(websocket.TextMessage, marshal)
	if err != nil {
		return
	}
}

var OnlineUser = make(map[uint]*websocket.Conn)

func WsChat(context *gin.Context) {
	var upgrader = websocket.Upgrader{} // use default options

	conn, err := upgrader.Upgrade(context.Writer, context.Request, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer conn.Close()
	for {
		mt, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		log.Printf("recv: %s", message)
		err = conn.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}

		var Ws request.WsReq
		switch Ws.Cmd {
		case "online":
			onlineuser(conn, message)
		case "send":
			senduser(conn, message)
		default:
			GetFail(conn, "500", "没有该指令")
			return
		}

	}

}

func senduser(conn *websocket.Conn, message []byte) {
	var WsSend request.WsSendReq
	err := json.Unmarshal(message, &WsSend)
	if err != nil {
		GetFail(conn, "500", "没有该指令")
		return
	}

	OnlineUser := OnlineUser[WsSend.Data.ToUserId]

	if OnlineUser == nil {
		GetFail(conn, "500", "用户不存在")
		return
	}

	SuccessFs(OnlineUser, WsSend.Data.Context)
	SuccessFs(conn, "发送成功")

	chat := models.Chats{
		ToUserId:   WsSend.Data.ToUserId,
		FormUserId: WsSend.Data.FormUserId,
		Content:    WsSend.Data.Context,
	}

	chat.Room()
	inits.DB.Create(&WsSend)

}

func onlineuser(conn *websocket.Conn, message []byte) {

	var WsOnline request.WsOnlineReq
	err := json.Unmarshal(message, &WsOnline)
	if err != nil {
		GetFail(conn, "500", "没有该指令")
		return
	}

	OnlineUser[WsOnline.Data.UserId] = conn
	SuccessFs(conn, "上线成功")

}

func WsC(context *gin.Context) {

}
